<template>
  <div v-show="!isMain && isView" class="view-equip-detail-wrap">
    <px-scrollbar :class="['view-equip-detail', { out: drawerType === 'out' }]">
      <px-button style="margin: 16px 0 24px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <div class="view-equip-title">出库详情</div>
      <div class="view-equip-wrap">
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">出库单号</div>
            <div class="text">{{ formValue.outNum || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">科室</div>
            <div class="text">{{ formValue.classNameDesc || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">领用人</div>
            <div class="text">{{ formValue.recipientName || "-" }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">用途</div>
            <div class="text">{{ formValue.usedDesc || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">种类</div>
            <div class="text">{{ formValue.categoryDesc || "-" }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">关联单据</div>
            <div class="text">{{ formValue.billNum || "-" }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item plus">
            <div class="label">关联设备</div>
            <div class="text">
              <ul>
                <li v-for="(item, index) in formValue.equipmentInfoDTOList" :key="index" class="mb-[4px]">
                  <span v-if="formValue.equipmentInfoDTOList.length !== 1">{{ `${index + 1}.` }}</span>
                  {{ `${item.eqpId} | ${item.eqpName} | ${item.positionNameAll}` }}
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">出库时间</div>
            <div class="text">{{ formValue.outDate || "-" }}</div>
          </div>
          <div class="view-equip-item large">
            <div class="label">备注</div>
            <div class="text">{{ formValue.remark || "-" }}</div>
          </div>
        </div>
      </div>
      <px-form v-if="drawerType === 'out'" ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <px-row>
          <px-col :span="8">
            <px-form-item label="退库人" prop="returnPeople" style="width: 100%">
              <px-select-v2
                v-model="formValue.returnPeople"
                filterable
                clearable
                :options="returnPeopleList"
                placeholder="请选择退库人"
                style="width: 100%"
                @change="returnPeopleChange"
              />
            </px-form-item>
          </px-col>
          <px-col :span="8">
            <px-form-item label="退库时间" prop="returnDate" style="width: 100%">
              <px-date-picker
                v-model="formValue.returnDate"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择退库时间"
                clearable
                :disabled-date="disabledDate"
                style="width: 100%"
              />
              <!-- :disabled-hours="disabledHours"
                :disabled-minutes="disabledMinutes"
                :disabled-seconds="disabledSeconds" -->
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
      <div :class="['view-equip-title', drawerType === 'out' ? 'mt-[14px]' : 'mt-[32px]']">出库列表</div>
      <px-table :data="formValue.inventoryDetailDTOList" class="equip-table" size="small" height="350" border style="margin-bottom: 24px">
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column v-if="drawerType === 'out'" prop="returnQuantity" label="退库数量" min-width="160" show-overflow-tooltip>
          <template #header>
            退库数量
            <px-icon style="cursor: pointer" @click="editReturnQuantity">
              <EditPen />
            </px-icon>
          </template>
          <template #default="scope">
            <div v-if="isReturnQuantity">
              {{ scope.row.returnQuantity }}
            </div>
            <px-input-number v-else v-model.number="scope.row.returnQuantity" :min="0" :max="scope.row.quantity" size="small" />
          </template>
        </px-table-column>
      </px-table>
    </px-scrollbar>
    <div v-if="drawerType === 'out'" class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, toRefs, watch, computed } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { getSparePartsOutbound, outSparePartsOutbound } from "@/api/equip/spareParts";

// 表单校验规则
const rules = computed(() => ({
  returnPeople: [{ required: true, message: "退库人不能为空", trigger: ["blur", "change"] }],
  returnDate: [{ required: true, message: "退库日期不能为空", trigger: ["blur", "change"] }]
}));
// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["queryTable", "backMainPage"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "sparePartsId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
const drawerType = computed(() => props.drawerType);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    id: "",
    outNum: "",
    recipientName: "",
    equipmentId: "",
    usedDesc: "",
    classNameDesc: "",
    categoryDesc: "",
    systemValDesc: "",
    billNum: "",
    outDate: "",
    remark: "",
    inventoryDetailDTOList: []
  },
  isReturnQuantity: true,
  returnPeopleList: [],
  tableColumns: [
    { prop: "categoryDesc", label: "种类", minWidth: "140", showOverflowTooltip: true, fixed: "left" },
    { prop: "sparePartCode", label: "编码", minWidth: "140", showOverflowTooltip: true },
    { prop: "sparePartName", label: "名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "120", showOverflowTooltip: true },
    { prop: "supplyModel", label: "厂商型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "warehousePositionDesc", label: "库位", minWidth: "120", showOverflowTooltip: true },
    { prop: "currentStock", label: "库存量", minWidth: "120", showOverflowTooltip: true },
    { prop: "quantity", label: "出库数量", minWidth: "120", showOverflowTooltip: true }
  ]
});
const { formValue, isReturnQuantity, returnPeopleList, tableColumns } = toRefs(state);
// 渲染设备
const renderEquip = data => {
  if (data) {
    return data.map(item => item.eqpName).join();
  }
  return "-";
};
// 禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() < new Date().getTime() - 8.64e7;
};
// 禁用时
const disabledHours = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.outDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 24; i++) {
      if (new Date().getHours() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用分
const disabledMinutes = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.outDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getMinutes() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用秒
const disabledSeconds = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.outDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getSeconds() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && props.isView) {
    formRef.value?.resetFields();
    isReturnQuantity.value = true;
    returnPeopleList.value = await getEmployeeIdAndName();
    const params = {
      id: props.sparePartsId
    };
    const data: any = await getSparePartsOutbound(params);
    formValue.value = { ...data };
  }
  // formValue.value.id = data.id;
  // formValue.value.outNum = data.outNum;
  // formValue.value.recipientName = data.recipientName;
  // formValue.value.equipmentInfoDTOList = data.equipmentInfoDTOList;
  // formValue.value.usedDesc = data.usedDesc;
  // formValue.value.categoryDesc = data.categoryDesc;
  // formValue.value.classNameDesc = data.classNameDesc;
  // formValue.value.systemValDesc = data.systemValDesc;
  // formValue.value.billNum = data.billNum;
  // formValue.value.outDate = data.outDate;
  // formValue.value.remark = data.remark;
  // formValue.value.inventoryDetailDTOList = data.inventoryDetailDTOList;
  // } else {
  //   formValue.value = {
  //     id: "",
  //     outNum: "",
  //     recipientName: "",
  //     equipmentId: "",
  //     usedDesc: "",
  //     classNameDesc: "",
  //     categoryDesc: "",
  //     systemValDesc: "",
  //     billNum: "",
  //     outDate: "",
  //     remark: "",
  //     inventoryDetailDTOList: []
  //   };
  // }
});
// 获取principalName
const returnPeopleChange = val => {
  const arr = returnPeopleList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.returnPeopleName = arr[0].label;
  }
};
// 编辑退库数量
const editReturnQuantity = () => {
  isReturnQuantity.value = !isReturnQuantity.value;
};
// 保存
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.inventoryDetailDTOList && formValue.value.inventoryDetailDTOList.length > 0) {
        PxMessageBox.confirm("是否已确认退库数量？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          draggable: true
        })
          .then(async () => {
            const arr = [];
            formValue.value.inventoryDetailDTOList.forEach(item => {
              arr.push({
                parePartId: item.id,
                returnQuantity: item.returnQuantity
              });
            });
            if (arr && arr.length > 0) {
              const flag = arr.every(item => {
                return item.returnQuantity !== "" && item.returnQuantity !== null;
              });
              if (!flag) {
                PxMessage.error("您尚有未填写的退库数量，请填写完成后进行提交！");
                return;
              }
            }
            const params = {
              id: formValue.value.id,
              returnDate: formValue.value.returnDate,
              returnPeople: formValue.value.returnPeople,
              returnPeopleName: formValue.value.returnPeopleName,
              inventoryDetailList: arr
            };
            await outSparePartsOutbound(params);
            PxMessage.success("退库成功！");
            emits("queryTable");
            emits("backMainPage");
          })
          .catch(() => {});
      } else {
        PxMessage.error("出库列表不能为空！");
      }
    }
  });
};
// 返回主页面
const backMainPage = () => {
  emits("backMainPage");
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/view-detail.scss");

.view-equip-detail-wrap {
  // position: relative;
  width: 100%;
  height: 100%;

  .view-equip-detail {
    height: calc(100vh - 126px);

    &.out {
      height: calc(100vh - 195px);
    }
  }

  .info-form-btns {
    position: absolute;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 68px;
    padding-right: 34px;
    background: #fff;
    box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
  }
}
</style>
